//
//  SampuxRegisterView.m
//  Sampux
//
//  Created by rzm on 16/7/4.
//  Copyright © 2016年 rzm. All rights reserved.
//

#import "SampuxRegisterView.h"
#import "IsValidateOrNot.h"
#import "SampuxCustomTextFiledView.h"
#import "SampuxValidationCodeView.h"
#import "SPDeleteTextFiledView.h"

@interface SampuxRegisterView ()<UITextFieldDelegate>
{
    NSUInteger _countDownTime;
    NSTimer *_timer;
    int _msgNumber;
}
@property (nonatomic, strong) UITextField *teleNumF;
@property (nonatomic, strong) UITextField *pwNumF;
@property (nonatomic, strong) UITextField *retypePWNumF ;
@property (nonatomic, strong) UITextField * codeF ;
@property (nonatomic, strong) UIButton *stateBtn;

@property (nonatomic, strong) SPDeleteTextFiledView *teleView ;
@property (nonatomic, strong) SampuxCustomTextFiledView *passwordView ;
@property (nonatomic, strong) SampuxCustomTextFiledView *retypePWView;

@property (nonatomic, strong) SampuxValidationCodeView *codeView;
@property(nonatomic,assign) BOOL isConnectOrNot;

@end
@implementation SampuxRegisterView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.isConnectOrNot = YES;

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestRegsiterCode:) name:NOTIFICATION_RESPONSE_REGISTER_VEGISTER object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestRegsiter:) name:NOTIFICATION_RESPONSE_REGISTER object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(connectFail) name:@"socketConnectFail" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(connectSuccess) name:@"socketConnectSuccess" object:nil];

        [self setupSubView];
    }
    return self;
}
- (void)connectSuccess
{
    self.isConnectOrNot = YES;
}

- (void)connectFail
{
    _isConnectOrNot = NO;
}

- (void)setupSubView
{
    CGFloat font;
    if (IS_IPHONE_4_OR_LESS) {
        font = 14.;
    }else if (IS_IPHONE_5_OR_LESS)
    {
        font = 14.;
    }else if (IS_IPHONE_6)
    {
        font = 16.;
    }else
    {
        font = 17.;
    }
    
    UIView *registerView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, kScreenWidth, self.height - 64)];
    [self addSubview:registerView];
    CGFloat THCustomSpaceX = self.width/2 - Sampux6WScale(SampuxCustomW)/2;
    
    UIButton *iconImage = [UIButton createButtonWithImage:imageNamed(@"sampux_logo")];
    iconImage.frame = CGRectMake( registerView.width * 0.2, registerView.height * 0.05, registerView.width * 0.6, Sampux6HScale(SampuxCustomH));
    [registerView addSubview:iconImage];
    iconImage.userInteractionEnabled = NO;

    CGRect teleNumRect = CGRectMake(THCustomSpaceX, CGRectGetMaxY(iconImage.frame)+ 35 , Sampux6WScale(SampuxCustomW), Sampux6HScale(SampuxCustomH));
    _teleView = [[SPDeleteTextFiledView alloc]initWithFrame:teleNumRect];
    [registerView addSubview:_teleView];
    [_teleView createDeleteTextFiledWithPlaceholder:@"输入手机号码" andLeftImage:@"make-user" andRightImage:@"delete"];
    _teleView.textFiled.secureTextEntry = NO;
    _teleView.textFiled.delegate = self;

    CGRect pwNumRect = CGRectMake(THCustomSpaceX, CGRectGetMaxY(_teleView.frame)+ SampuxMargin,Sampux6WScale(SampuxCustomW), Sampux6HScale(SampuxCustomH));
    _passwordView = [[SampuxCustomTextFiledView alloc]initWithFrame:pwNumRect];
    [registerView addSubview:_passwordView];
    [_passwordView createUserTextFiledWithPlaceholder:@"输入密码" andLeftImage:@"lock" andRightImage:@"eye"];
    _passwordView.warnBtn.hidden = YES;
    _passwordView.textFiled.secureTextEntry = YES;
    _passwordView.textFiled.delegate = self;

    
    CGRect retypePWNumRect = CGRectMake(THCustomSpaceX, CGRectGetMaxY(_passwordView.frame)+ SampuxMargin, Sampux6WScale(SampuxCustomW), Sampux6HScale(SampuxCustomH));
    _retypePWView = [[SampuxCustomTextFiledView alloc]initWithFrame:retypePWNumRect];
    [registerView addSubview:_retypePWView];
    [_retypePWView createUserTextFiledWithPlaceholder:@"再次输入密码" andLeftImage:@"lock" andRightImage:@"eye"];
    _retypePWView.warnBtn.hidden = YES;
    _retypePWView.textFiled.secureTextEntry = YES;
    _retypePWView.textFiled.delegate = self;
    
    
    _codeView = [[SampuxValidationCodeView alloc]initWithFrame:CGRectMake(THCustomSpaceX, CGRectGetMaxY(_retypePWView.frame)+ SampuxMargin,  Sampux6WScale(SampuxCustomW), Sampux6HScale(SampuxCustomH))];
    [registerView addSubview:_codeView];
    [_codeView createValidationCodeWithPlaceholder:@"输入验证码" andLeftImage:@"feedBackCode" andRightImage:@"eye" andcodeBtn:@"获取验证码"];
    _codeView.codeF.secureTextEntry = YES;
    _codeView.codeF.delegate = self;
    [_codeView.codeBtn addTarget:self action:@selector(sendValidationCode) forControlEvents:UIControlEventTouchUpInside];
    
    CGSize maxSize = CGSizeMake(MAXFLOAT, _codeView.height *0.9);
    NSString *agreementStr = @"我已阅读并同意《桑普电器用户协议》";
    CGSize Size = [SampuxGlobalTool getSizeWithString:agreementStr andFont:THFont(font - 1) andMaxSize:maxSize];
    
    UILabel *registerLab = [UILabel createLabelWithFrame:CGRectMake(registerView.width/2- Size.width/2 + _codeView.height/2 - 5, _codeView.bottom + Sampux6HScale(20), Size.width, maxSize.height) textColor:THWhiteAlplaColor(0.8) font:[UIFont systemFontOfSize:(font - 1)]];//需要改动lab的frame
    [registerView addSubview:registerLab];
//    registerLab.backgroundColor = RandomColor;
    registerLab.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(agreementTapClick)];
    [registerLab addGestureRecognizer:tap];
    registerLab.attributedText = [SampuxGlobalTool addAttributeline:agreementStr];
    registerLab.textColor = THWhiteAlplaColor(0.6);
    registerLab.numberOfLines = 1;
    
    _stateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _stateBtn.frame = CGRectMake(registerLab.left -  Sampux6WScale(30) - 10, registerLab.y , Sampux6WScale(30),  _codeView.height *0.9);//需要改动btn的frame.x
    [_stateBtn setImage:imageNamed(@"stateBtn_normal") forState:UIControlStateNormal];
    [self.stateBtn setImage:imageNamed(@"stateBtn_selected") forState:UIControlStateSelected];
    _stateBtn.layer.masksToBounds = YES;
    _stateBtn.selected = YES;
    [_stateBtn addTarget:self action:@selector(stateBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [registerView addSubview:_stateBtn];
    _stateBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    _stateBtn.hitTestEdgeInsets = UIEdgeInsetsMake(- 10 , -10, -10, 0);

    UIButton *registerBtn = [UIButton createButtonWithTitle:@"确定" frame:CGRectMake(self.width/2 - Sampux6WScale(354/2)/2, CGRectGetMaxY(_stateBtn.frame)+ Sampux6HScale(30), Sampux6WScale(354/2), Sampux6HScale(45)) titleFont:THFont(font) titleColor:THDeFaultBlueColor];
    [registerView addSubview:registerBtn];
    [registerBtn setCorner:registerBtn.height/2];
    [registerBtn addTarget:self action:@selector(registerBtnClick) forControlEvents:UIControlEventTouchUpInside];
    registerBtn.layer.borderColor = THWhiteAlplaColor(0.6).CGColor;
    registerBtn.layer.borderWidth = 1;
    
//    UIButton *btn = [UIButton createButton];
//    btn.frame = CGRectMake(self.width/2 - 30, registerBtn.bottom + 10, 60, Sampux6HScale(30));
//    [registerView addSubview:btn];
//    btn.titleLabel.font = THFont(font);
//    [btn setTitle:@"已有账号" forState:UIControlStateNormal];
//    [btn addTarget:self action:@selector(existAccountBtnClick) forControlEvents:UIControlEventTouchUpInside];
}

- (void)sendValidationCode
{
    BOOL isMobile = [IsValidateOrNot isValidateMobile:self.teleView.textFiled.text];
    BOOL isEmail = [IsValidateOrNot isValidateEmail:self.teleView.textFiled.text];
    BOOL isPassword = [IsValidateOrNot isValidatePassword:self.passwordView.textFiled.text];
    
    if ([self.teleView.textFiled.text isEqualToString: @""] || self.teleView.textFiled.text.length == 0){
        [SVProgressHUD showErrorWithStatus:@"用户名必须为手机号"];
    }else
    {
        if (!isMobile&&!isEmail)
        {
            [SVProgressHUD showErrorWithStatus:@"用户名必须为手机号"];
        }else
        {
            if (self.isConnectOrNot == NO) {
                [SVProgressHUD showErrorWithStatus:@"网络未连接，请检查您的网络连接设置"];
            }else
            {
                _countDownTime = 60;
                //调用后台连接，获取验证码
                [GBInterMaster_CommForSystem requestUserRegisterVegister:0 withAccount:self.teleView.textFiled.text];
            }
        }
    }

}
- (void)existAccountBtnClick
{
    if (self.existBtnBlock) {
        self.existBtnBlock();
    }
}
/**
 *  创建定时器
 */
- (void)createTimer
{
//    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeCountDown) userInfo:nil repeats:YES];

}
/**
 *  定时器减到0
 */
- (void)timeCountDown
{
    if (_countDownTime == 1) {
        [self.codeView.codeBtn setTitle:@"重新发送" forState:UIControlStateNormal];
        self.codeView.codeBtn.userInteractionEnabled = YES;
        [_timer invalidate];
        _timer = nil;
    }else
    {
        _countDownTime--;
        NSString *timeStr = [NSString stringWithFormat:@"重新发送%.2lu",(unsigned long)_countDownTime];
        [self.codeView.codeBtn setTitle:timeStr forState:UIControlStateNormal];
        self.codeView.codeBtn.userInteractionEnabled = NO;
    }
//    NSLog(@"_countDownTime====%d",_countDownTime);
}

- (void)stateBtnClick
{
    self.stateBtn.selected = !self.stateBtn.selected;
//    if (self.stateBtn.selected == YES) {
//        [self.stateBtn setImage:imageNamed(@"stateBtn_selected") forState:UIControlStateNormal];
//        
//    }else
//    {
//        [self.stateBtn setImage:imageNamed(@"stateBtn_normal") forState:UIControlStateNormal];
//    }
}

- (void)agreementTapClick
{
    if (self.agreementTapBlock) {
        self.agreementTapBlock();
    }
}

- (void)registerBtnClick
{
    BOOL isMobile = [IsValidateOrNot isValidateMobile:self.teleView.textFiled.text];
    BOOL isEmail = [IsValidateOrNot isValidateEmail:self.teleView.textFiled.text];
    BOOL isPassword = [IsValidateOrNot isValidatePassword:self.passwordView.textFiled.text];
    if ([self.teleView.textFiled.text isEqualToString: @""] || self.teleView.textFiled.text.length == 0){
        [SVProgressHUD showErrorWithStatus:@"用户名必须为手机号"];
//        [MBProgressHUD showError:@"用户名必须为手机号或者邮箱"];
    } else {
        if (!isMobile&&!isEmail)
        {
            [SVProgressHUD showErrorWithStatus:@"用户名必须为手机号"];
//            [MBProgressHUD showError:@"用户名必须为手机号或者邮箱"];
        } else {
            if ([self.passwordView.textFiled.text isEqualToString: @""]|| self.passwordView.textFiled.text.length == 0)
            {
                [SVProgressHUD showErrorWithStatus:@"密码必须为7~16位长度的字母，数字，下划线"];
//                [MBProgressHUD showError:@"密码必须为7~16位长度的字母，数字，下划线"];
            } else {
                if (!isPassword) {
                    [SVProgressHUD showErrorWithStatus:@"密码必须为7~16位长度的字母，数字，下划线"];
//                    [MBProgressHUD showError:@"密码必须为7~16位长度的字母，数字，下划线"];
                } else {
                    if ([self.passwordView.textFiled.text isEqualToString: self.retypePWView.textFiled.text]) {
                        
                        if ([self.codeView.codeF.text isEqualToString: @""]|| self.codeView.codeF.text.length == 0)
                        {
                            [SVProgressHUD showErrorWithStatus:@"请输入验证码"];
//                                [MBProgressHUD showError:@"验证码错误"];
                        } else {
                            if (self.stateBtn.selected == NO) {
                                [SVProgressHUD showErrorWithStatus:@"阅读并同意《桑普电器用户协议》"];
    //                            [MBProgressHUD showError:@"阅读并同意《桑普电器用户协议》"];
                            } else {
                                if (self.isConnectOrNot == NO) {
                                    [SVProgressHUD showErrorWithStatus:@"网络未连接，请检查您的网络连接设置"];
                                } else {
                                    [GBInterMaster_CommForSystem requestUserRegister:0 withPassword:_passwordView.textFiled.text withCheckCode:_codeView.codeF.text];
                                }
                            }
                        }
                    } else {
                        [SVProgressHUD showErrorWithStatus:@"两次密码不一致"];
//                        [MBProgressHUD showError:@"两次密码不一致"];
                    }
                }
            }
        }
    }
}

- (void)requestRegsiterCode:(NSNotification* )notification
{
    id userInfo = [notification userInfo];
    if(userInfo == nil){
        return;
    }
    NSDictionary * result = userInfo;
    int msgNumber = [[result objectForKey:@"msgNumber"] intValue];
    _msgNumber = msgNumber;
    int responseCode = [[result objectForKey:@"responseCode"] intValue];
    NSLog(@"requestRegsiterCode == 结果，消息序号：%d，响应码：%x",msgNumber,responseCode);
    if (responseCode == 0x00) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self createTimer];
        });
    } else {
        [SVProgressHUD showErrorWithStatus:[SPResponseCodePrompt responseCodePrompt:responseCode]];
        if (responseCode == 0x2B) {
            [[NSNotificationCenter defaultCenter]postNotificationName:@"remeberTeleWithExist" object:_teleView.textFiled.text];
        }
//        [MBProgressHUD showError:[SPResponseCodePrompt responseCodePrompt:responseCode]];
    }
}

- (void)requestRegsiter:(NSNotification* )notification
{
    id userInfo = [notification userInfo];
    if(userInfo == nil){
        return;
    }
    NSDictionary * result = userInfo;
    int msgNumber = [[result objectForKey:@"msgNumber"] intValue];
    _msgNumber = msgNumber;
    int responseCode = [[result objectForKey:@"responseCode"] intValue];
    NSLog(@"requestRegsiter == 结果，消息序号：%d，响应码：%x",msgNumber,responseCode);
    if (responseCode == 0x00) {
        [SVProgressHUD showSuccessWithStatus:@"注册成功"];
//        [MBProgressHUD showError:@"注册成功"];
        if (self.registerBtnBlock) {
            self.registerBtnBlock(_teleView.textFiled.text,_passwordView.textFiled.text);
        }
    } else {
        [SVProgressHUD showErrorWithStatus:[SPResponseCodePrompt responseCodePrompt:responseCode]];
       
//        [MBProgressHUD showError:[SPResponseCodePrompt responseCodePrompt:responseCode]];
    }
}

#pragma -mark textFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == _codeView.codeF) {
        NSString * toBeString = [_codeView.codeF.text stringByReplacingCharactersInRange:range withString:string];
        if (toBeString.length > 6 && range.length!=1){
            textField.text = [toBeString substringToIndex:6];
            return NO;
        }
        return YES;
    } else if (textField == self.passwordView.textFiled ||textField == self.retypePWView.textFiled){
        NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
        
        if (toBeString.length > 16 && range.length < 7){
            textField.text = [toBeString substringToIndex:16];
            return NO;
        }
        return YES;
    } else {
        return YES;
    }
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    [self layoutIfNeeded];
    self.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight );
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self layoutIfNeeded];
    CGFloat keyboardHeight = 216.0f;
    self.frame = CGRectMake(0, -60 , self.width, kScreenHeight + 60);
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [self layoutIfNeeded];
    self.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    self.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight );
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}
/**
 *  在试图销毁的时候销毁定时器
 */
- (void)dealloc{
    if (_timer.isValid) {
        [_timer invalidate];
        _timer = nil;
    }

    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
